package com.jcfk.eam.service.main;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.core.utils.IdUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.dao.main.EamInspectionTaskDao;
import com.jcfk.eam.dao.main.EamPointCheckOrderDao;
import com.jcfk.eam.domain.dto.base.EamSopItemDTO;
import com.jcfk.eam.domain.dto.base.EamSopItemValueDTO;
import com.jcfk.eam.domain.dto.main.*;
import com.jcfk.eam.domain.po.base.EamSparePart;
import com.jcfk.eam.domain.po.main.*;
import com.jcfk.eam.domain.query.base.EamSopItemQuery;
import com.jcfk.eam.domain.query.main.EamPointCheckOrderQuery;
import com.jcfk.eam.service.base.EamSopItemService;
import com.jcfk.eam.service.base.EamSopStandardService;
import com.jcfk.eam.service.base.EamSparePartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 资产点检工单
 *
 * @author yrl
 * @email
 * @date 2024-11-06
 */
@Service
public class EamPointCheckOrderService extends BaseService<EamPointCheckOrderDao, EamPointCheckOrder> {

    @Autowired
    private EamPointCheckDetailService eamPointCheckDetailService;

    @Autowired
    private EamPointCheckDetailImgService eamPointCheckDetailImgService;

    @Autowired
    private EamSopStandardService eamSopStandardService;

    @Autowired
    private EamSopItemService eamSopItemService;

    @Autowired
    private EamInspectionTaskDao eamInspectionTaskDao;

    @Autowired
    private EamSparePartService eamSparePartService;

    @Resource
    private EamRepairOrderPartService eamRepairOrderPartService;

    /**
     * EamPointCheckOrder分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamPointCheckOrderDTO> queryByPage(DataPage<EamPointCheckOrderDTO> page, EamPointCheckOrderQuery query) {
        query.setAssetCode(StrUtil.isNotEmpty(query.getAssetCode()) ? query.getAssetCode() + "%" : query.getAssetCode());
        query.setOrderNo(StrUtil.isNotEmpty(query.getOrderNo()) ? query.getOrderNo() + "%" : query.getOrderNo());
        query.setExecutePersonName(StrUtil.isNotEmpty(query.getExecutePersonName()) ? query.getExecutePersonName() + "%" : query.getExecutePersonName());
        // 分页查询
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }

    /**
     * EamPointCheckOrder分页查询(计划)
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamPointCheckOrderDTO> queryByPlan(DataPage<EamPointCheckOrderDTO> page, EamPointCheckOrderQuery query) {
        query.setAssetCode(StrUtil.isNotEmpty(query.getAssetCode()) ? query.getAssetCode() + "%" : query.getAssetCode());
        query.setOrderNo(StrUtil.isNotEmpty(query.getOrderNo()) ? query.getOrderNo() + "%" : query.getOrderNo());
        query.setExecutePersonName(StrUtil.isNotEmpty(query.getExecutePersonName()) ? query.getExecutePersonName() + "%" : query.getExecutePersonName());
        // 分页查询
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }

    /**
     * 根据任务分页查询设备巡检工单
     */
    public DataPage<EamPointCheckOrderDTO> queryByTask(DataPage<EamPointCheckOrderDTO> page, EamPointCheckOrderQuery query) {
        // 分页查询
        query.setLocationId(StringUtils.isEmpty(query.getLocationId()) ? query.getLocationId() : "%" + query.getLocationId() + "%");
        page = this.baseMapper.queryByTask(page, query);
        return page;
    }

    /**
     * EamPointCheckOrder分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamPointCheckOrderDTO> queryMyList(DataPage<EamPointCheckOrderDTO> page, EamPointCheckOrderQuery query) {
        query.setAssetCode(StrUtil.isNotEmpty(query.getAssetCode()) ? "%" + query.getAssetCode() + "%" : query.getAssetCode());
        query.setOrderNo(StrUtil.isNotEmpty(query.getOrderNo()) ? "%" + query.getOrderNo() + "%" : query.getOrderNo());
        query.setSearchContent(StrUtil.isNotEmpty(query.getSearchContent()) ? "%" + query.getSearchContent() + "%" : query.getSearchContent());
        query.setExecutePersonName(StrUtil.isNotEmpty(query.getExecutePersonName()) ? query.getExecutePersonName() + "%" : query.getExecutePersonName());
        // 分页查询
        page = this.baseMapper.queryMyList(page, query);
        return page;
    }

    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EamPointCheckOrderDTO>
     */
    public List<EamPointCheckOrderDTO> getList(EamPointCheckOrderQuery query) {
        // 查询条件
        QueryWrapper<EamPointCheckOrder> qw = new QueryWrapper<>();
        qw.lambda().eq(EamPointCheckOrder::getDeleted, 0);
        qw.lambda().eq(!StrUtil.isEmpty(query.getPlanId()), EamPointCheckOrder::getPlanId, query.getPlanId());
        qw.lambda().eq(!StrUtil.isEmpty(query.getSopTypeId()), EamPointCheckOrder::getSopTypeId, query.getSopTypeId());
        qw.lambda().eq(!StrUtil.isEmpty(query.getSopStandardId()), EamPointCheckOrder::getSopStandardId, query.getSopStandardId());
        qw.lambda().eq(!StrUtil.isEmpty(query.getAssetId()), EamPointCheckOrder::getAssetId, query.getAssetId());
        qw.lambda().eq(null != query.getOrderStatus(), EamPointCheckOrder::getOrderStatus, query.getOrderStatus());
        // 查询数据
        List<EamPointCheckOrder> list = super.list(qw);

        return convertList(list, EamPointCheckOrderDTO.class);
    }

    /**
     * 获取根据关联id详情表列表
     *
     * @param query 查询条件
     * @return List<EamPointCheckOrderDTO>
     */
    public List<EamPointCheckDetailDTO> getDetails(EamPointCheckOrderQuery query) {
        EamSopItemQuery sopItemQuery = new EamSopItemQuery();
        sopItemQuery.setStandardId(query.getSopStandardId());
        List<EamSopItemDTO> sopItems = eamSopItemService.getList(sopItemQuery);
        // 查询数据
        List<EamPointCheckDetailDTO> list = eamPointCheckDetailService.listIncludeImg(query.getId());
        for (EamPointCheckDetailDTO checkDetail : list) {
            Optional<EamSopItemDTO> sopItemResult = sopItems.stream().filter(p -> p.getId().equals(checkDetail.getSopItemId())).findAny();
            if (sopItemResult.isPresent()) {
                checkDetail.setSopItem(sopItemResult.get());
            }
        }
        return list;
    }

    /**
     * 判断EamPointCheckOrder是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamPointCheckOrderDTO dto) {
        QueryWrapper<EamPointCheckOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("order_no", dto.getOrderNo());
        if (!StringUtils.isEmpty(dto.getId())) queryWrapper.ne("id", dto.getId());
        Integer count = this.count(queryWrapper);

        if (count > 0) return RetResult.fail("工单编号已存在");
        return RetResult.ok();
    }

    /**
     * 插入资产点检工单
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamPointCheckOrderDTO dto) {

        // 保存
        EamPointCheckOrder item = new EamPointCheckOrder();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);

        // 保存明细表
        eamPointCheckDetailService.saveBatch(dto.getDetails(), item.getId());
    }

    /**
     * 获取点简单
     *
     * @param id
     * @return
     */
    public EamPointCheckOrderDTO getOrder(String id) {
        //获取点检单信息
        EamPointCheckOrderDTO order = this.get(id);

        //获取点检明细信息
        EamPointCheckOrderQuery detailQuery = new EamPointCheckOrderQuery();
        detailQuery.setId(id);
        List<EamPointCheckDetailDTO> details = this.getDetails(detailQuery);
        order.setDetails(details);

        //获取点检标准信息
        EamPointCheckResultDTO eamPointCheckResultDTO = eamSopStandardService.getSopStandard(order.getSopStandardId());
        List<EamSopItemDTO> items = eamPointCheckResultDTO.getItemDTOS();

        for (EamPointCheckDetailDTO detail : order.getDetails()) {
            Optional<EamSopItemDTO> itemResult = items.stream().filter(p -> p.getId().equals(detail.getSopItemId())).findFirst();
            if (itemResult.isPresent()) {
                EamSopItemDTO sopItem = itemResult.get();

                if (sopItem.getStandardValue().equals("1")) {
                    //测量项
                    if (StrUtil.isNotEmpty(sopItem.getStandardMinValue()) && StrUtil.isNotEmpty(sopItem.getStandardMaxValue())) {
                        detail.setSopItemStandard(sopItem.getStandardMinValue() + "-" + sopItem.getStandardMaxValue());
                    }
                    if (StrUtil.isNotEmpty(sopItem.getStandardValueUnit())) {
                        detail.setSopItemStandard(detail.getSopItemStandard() + sopItem.getStandardValueUnit());
                    }
                } else {
                    //非测量项
                }

                detail.setSopItem(sopItem);
            }
        }

        //查询使用备件情况
        QueryWrapper<EamRepairOrderPart> partQw = new QueryWrapper<>();
        partQw.lambda().eq(EamRepairOrderPart::getRepairId, id);
        List<EamRepairOrderPart> parts = eamRepairOrderPartService.list(partQw);

        List<String> ids = parts.stream().map(EamRepairOrderPart::getSparePartId).collect(Collectors.toList());

        List<EamRepairOrderPartDTO> partDtoList = convertList(parts, EamRepairOrderPartDTO.class);
        order.setParts(new ArrayList<>());
        if (ids.size() > 0) {
            QueryWrapper<EamSparePart> partQueryWrapper = new QueryWrapper<>();
            partQueryWrapper.in("id", ids);
            List<EamSparePart> eamSpareParts = eamSparePartService.list(partQueryWrapper);
            Map<String, EamSparePart> map = new HashMap<>();
            for (EamSparePart eamSparePart : eamSpareParts) {
                map.put(eamSparePart.getId(), eamSparePart);
            }

            for (EamRepairOrderPartDTO partDTO : partDtoList) {
                EamSparePart eamSparePart = map.get(partDTO.getSparePartId());
                if (eamSparePart != null) {
                    partDTO.setSpareCode(eamSparePart.getSpareCode());
                    partDTO.setSpareName(eamSparePart.getSpareNmae());
                    partDTO.setSpareType(eamSparePart.getSpareType());
                    partDTO.setSpareUnit(eamSparePart.getSpareUnit());
                    order.getParts().add(partDTO);
                }
            }
        }

        return order;
    }

    /**
     * 快速提交巡检通过
     *
     * @param order
     */
    @Transactional(rollbackFor = Exception.class)
    public void submitNormal(EamPointCheckOrderDTO order) {
        order = this.getOrder(order.getId());
        order.setOrderStatus(2);

        //设置默认值
        for (EamPointCheckDetailDTO detail : order.getDetails()) {
            if (detail.getSopItem().getStandardValue().equals("2")) {
                for (EamSopItemValueDTO sopItemDetail : detail.getSopItem().getDetails()) {
                    if (sopItemDetail.getResultValue().equals("1")) {
                        //设备默认为合格
                        detail.setSopItemValue(sopItemDetail.getStandardValue());
                    }
                }
            }
        }

        this.saveOrder(order);

        //设置任务工单统计信息
        if (StrUtil.isNotEmpty(order.getInspectionTaskId())) {
            CheckOrderCountDTO checkOrderCount = this.baseMapper.getOrderCount(order.getInspectionTaskId());
            EamInspectionTask inspectionTask = this.eamInspectionTaskDao.selectById(order.getInspectionTaskId());
            inspectionTask.setNotInspectedNumber(checkOrderCount.getNotInspectionCount());
            inspectionTask.setExceptionNumber(checkOrderCount.getExceptionCount());
            if (checkOrderCount.getNotInspectionCount() == 0) {
                inspectionTask.setTaskStatus(2);
                inspectionTask.setEndExecuteTime(new Date());
            }
            this.eamInspectionTaskDao.updateById(inspectionTask);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void submit(EamPointCheckOrderDTO order) {
        order.setOrderStatus(2);
        this.saveOrder(order);

        //设置任务工单统计信息
        if (StrUtil.isNotEmpty(order.getInspectionTaskId())) {
            CheckOrderCountDTO checkOrderCount = this.baseMapper.getOrderCount(order.getInspectionTaskId());
            EamInspectionTask inspectionTask = this.eamInspectionTaskDao.selectById(order.getInspectionTaskId());
            inspectionTask.setNotInspectedNumber(checkOrderCount.getNotInspectionCount());
            inspectionTask.setExceptionNumber(checkOrderCount.getExceptionCount());
            if (checkOrderCount.getNotInspectionCount() == 0) {
                inspectionTask.setTaskStatus(2);
                inspectionTask.setEndExecuteTime(new Date());
            }
            this.eamInspectionTaskDao.updateById(inspectionTask);
        }
    }

    /**
     * 保存点检单
     *
     * @param order
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveOrder(EamPointCheckOrderDTO order) {

        EamPointCheckOrder eamPointCheckOrder = this.getById(order.getId());

        if (eamPointCheckOrder == null) {
            eamPointCheckOrder = new EamPointCheckOrder();
            eamPointCheckOrder.setOrderNo(order.getOrderNo());
            eamPointCheckOrder.setSopTypeId(order.getSopTypeId());
            eamPointCheckOrder.setSopTypeCode(order.getSopTypeCode());
            eamPointCheckOrder.setSopStandardId(order.getSopStandardId());
            eamPointCheckOrder.setSopStandardCode(order.getSopStandardCode());
            eamPointCheckOrder.setAssetId(order.getAssetId());
            eamPointCheckOrder.setAssetCode(order.getAssetCode());
            eamPointCheckOrder.setAssetName(order.getAssetName());
            eamPointCheckOrder.setExecutePersonId(order.getExecutePersonId());
            eamPointCheckOrder.setExecutePersonName(order.getExecutePersonName());
            eamPointCheckOrder.setAssetKind(order.getAssetKind());
        }
        eamPointCheckOrder.setProblemDesc(order.getProblemDesc());
        eamPointCheckOrder.setWorkTime(new Date());
        eamPointCheckOrder.setOrderStatus(order.getOrderStatus());

        List<String> detailIds = new ArrayList<>();
        List<EamPointCheckDetailImgDTO> images = new ArrayList<>();
        for (EamPointCheckDetailDTO detail : order.getDetails()) {
            if (detail.getSopItemValue() != null) {
                if (detail.getSopItem().getStandardValue().equals("1")) {
                    // 测量项
                    if (!StrUtil.isEmpty(detail.getSopItem().getStandardMinValue()) && !StrUtil.isEmpty(detail.getSopItem().getStandardMaxValue())) {
                        Double itemValue = Double.valueOf(detail.getSopItemValue());
                        Double standardMinValue = Double.valueOf(detail.getSopItem().getStandardMinValue());
                        Double standardMaxValue = Double.valueOf(detail.getSopItem().getStandardMaxValue());
                        if (itemValue >= standardMinValue && itemValue <= standardMaxValue) {
                            detail.setSopItemResult("1");
                        } else {
                            detail.setSopItemResult("0");
                        }
                    }
                } else {
                    // 非测量项
                    for (int i = 0; i < detail.getSopItem().getDetails().size(); i++) {
                        if (detail.getSopItemValue() != null && detail.getSopItemValue().equals(detail.getSopItem().getDetails().get(i).getStandardValue())) {
                            EamSopItemValueDTO eamSopItemValueDTO = detail.getSopItem().getDetails().get(i);
                            detail.setSopItemValue(eamSopItemValueDTO.getStandardValue());
                            detail.setSopItemResult(eamSopItemValueDTO.getResultValue());
                        }
                    }
                }
            }

            detailIds.add(detail.getId());
            for (EamPointCheckDetailImgDTO imageDto : detail.getImages()) {
                imageDto.setPointCheckDetailId(detail.getId());
                images.add(imageDto);
            }
        }

        //计算工单结果
        Long noPassCount = order.getDetails().stream().filter(p -> StrUtil.isNotEmpty(p.getSopItemResult()) && p.getSopItemResult().equals("0")).count();
        eamPointCheckOrder.setCheckResult(noPassCount > 0 ? 0 : 1);
        eamPointCheckOrder.setExceptionNumber(Integer.parseInt(noPassCount.toString()));
        //计算未检项
        Long notInspectionCount = order.getDetails().stream().filter(p -> StrUtil.isEmpty(p.getSopItemValue())).count();
        eamPointCheckOrder.setNotInspectedNumber(Integer.parseInt(notInspectionCount.toString()));
        this.setDefaultValue(eamPointCheckOrder);
        if (StrUtil.isEmpty(eamPointCheckOrder.getId())) {
            this.baseMapper.insert(eamPointCheckOrder);
        } else {
            this.baseMapper.updateById(eamPointCheckOrder);
        }

        //保存使用备件
        if (order.getParts() != null && order.getParts().size() > 0) {
            QueryWrapper<EamRepairOrderPart> partQueryWrapper = new QueryWrapper<>();
            partQueryWrapper.lambda().eq(EamRepairOrderPart::getRepairId, order.getId());
            eamRepairOrderPartService.remove(partQueryWrapper);
            List<EamRepairOrderPart> partList = new ArrayList<>();
            for (EamRepairOrderPartDTO partDTO : order.getParts()) {
                EamRepairOrderPart orderPart = new EamRepairOrderPart();
                orderPart.setRepairId(eamPointCheckOrder.getId());
                orderPart.setSparePartId(partDTO.getSparePartId());
                orderPart.setSparePartNumber(partDTO.getSparePartNumber());
                eamRepairOrderPartService.setDefaultValue(orderPart);
                partList.add(orderPart);
            }
            if (partList.size() > 0) {
                eamRepairOrderPartService.saveBatch(partList);
            }
        }
        //更新任务信息
        if (StrUtil.isNotEmpty(eamPointCheckOrder.getInspectionTaskId())) {
            EamInspectionTask inspectionTask = this.eamInspectionTaskDao.selectById(eamPointCheckOrder.getInspectionTaskId());
            if (inspectionTask.getStartExecuteTime() == null) {
                inspectionTask.setStartExecuteTime(new Date());
                inspectionTask.setTaskStatus(1);
                inspectionTask.setLastUpdatedUserId(SecurityUtils.getUserId());
                inspectionTask.setLastUpdatedUserName(SecurityUtils.getUserName());
                inspectionTask.setLastUpdateTime(new Date());
                this.eamInspectionTaskDao.updateById(inspectionTask);
            }
        }

        for (EamPointCheckDetailDTO detail : order.getDetails()) {
            detail.setOrderId(eamPointCheckOrder.getId());
        }
        order.setId(eamPointCheckOrder.getId());

        if (order.getDetails().size() > 0) eamPointCheckDetailService.saveBatch(order.getDetails(), order.getId());
        if (images.size() > 0) eamPointCheckDetailImgService.saveBatch(images, detailIds);
    }

    /**
     * 生成点检单
     */
    @Transactional(rollbackFor = Exception.class)
    public void buildOrder(OrderBuildRequest buildRequest, EamAssetInfo eamAssetInfo) {
        EamPointCheckResultDTO sopStandard = null;
        if (StrUtil.isNotEmpty(buildRequest.getStandardId())) {
            sopStandard = eamSopStandardService.getSopStandard(buildRequest.getStandardId());
        } else {
            sopStandard = eamSopStandardService.getSopStandard(buildRequest.getSopTypeCode(), buildRequest.getStandardCode());
        }
        buildOrder(buildRequest, eamAssetInfo, sopStandard);
    }

    /**
     * 生成点检单
     */
    @Transactional(rollbackFor = Exception.class)
    public void buildOrder(OrderBuildRequest buildRequest, EamAssetInfo eamAssetInfo, EamPointCheckResultDTO sopStandard) {
        // 保存尺寸点检信息
        EamPointCheckOrder eamPointCheckOrder = new EamPointCheckOrder();
        eamPointCheckOrder.setInspectionTaskId(buildRequest.getTaskId());
        eamPointCheckOrder.setPlanId(buildRequest.getPlanId());
        eamPointCheckOrder.setPlanTime(buildRequest.getPlanWorkTime());
        eamPointCheckOrder.setExecutePersonId(buildRequest.getExecutePersonId());
        eamPointCheckOrder.setExecutePersonName(buildRequest.getExecutePersonName());
        eamPointCheckOrder.setOrderStatus(buildRequest.getOrderStatus());
        eamPointCheckOrder.setAssetKind(buildRequest.getAssetKind());
        eamPointCheckOrder.setOrderNo(buildRequest.getOrderNo());
        eamPointCheckOrder.setNotInspectedNumber(sopStandard.getItemDTOS().size());
        eamPointCheckOrder.setExceptionNumber(0);
        eamPointCheckOrder.setSopTypeId(sopStandard.getSopTypeId());
        eamPointCheckOrder.setSopTypeCode(sopStandard.getSopTypeCode());
        eamPointCheckOrder.setSopStandardId(sopStandard.getId());
        eamPointCheckOrder.setSopStandardCode(sopStandard.getStandardCode());
        eamPointCheckOrder.setAssetId(eamAssetInfo.getId());
        eamPointCheckOrder.setAssetCode(eamAssetInfo.getAssetCode());
        eamPointCheckOrder.setAssetName(eamAssetInfo.getAssetName());
        eamPointCheckOrder.setOrderStatus(buildRequest.getOrderStatus());
        eamPointCheckOrder.setExecutePersonId(buildRequest.getExecutePersonId());
        eamPointCheckOrder.setExecutePersonName(buildRequest.getExecutePersonName());

        this.setDefaultValue(eamPointCheckOrder);
        this.save(eamPointCheckOrder);

        List<EamPointCheckDetail> details = new ArrayList<>();
        int seq = 1;
        for (EamSopItemDTO itemDTO : sopStandard.getItemDTOS()) {
            EamPointCheckDetail detail = new EamPointCheckDetail();
            detail.setId(IdUtils.simpleUUID());
            detail.setSeq(seq);
            detail.setOrderId(eamPointCheckOrder.getId());
            detail.setSopItemId(itemDTO.getId());
            detail.setSopItemName(itemDTO.getSopItemName());
            detail.setSopItemValue(itemDTO.getSaveValue());
            eamPointCheckDetailService.setDefaultValue(detail);

            if (buildRequest.getTaskKind().equals("ri")) {
                //生成巡检工单设置默认值
                if (itemDTO.getStandardValue().equals("2")) {
                    for (EamSopItemValueDTO sopItemDetail : itemDTO.getDetails()) {
                        if (sopItemDetail.getResultValue().equals("1")) {
                            //设备默认为合格
                            detail.setSopItemValue(sopItemDetail.getStandardValue());
                        }
                    }
                }
            }

            details.add(detail);
            seq++;
        }

        if (details.size() > 0) eamPointCheckDetailService.saveBatch(details);
    }

    /**
     * 更新资产点检工单
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamPointCheckOrderDTO dto) {

        // 保存
        EamPointCheckOrder item = new EamPointCheckOrder();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);

        // 设置关联主键
        for (EamPointCheckDetailDTO detail : dto.getDetails()) {
            detail.setSopItemId(item.getId());
        }
        // 保存明细表
        eamPointCheckDetailService.saveBatch(dto.getDetails(), item.getId());
    }


    /**
     * 根据批量主键删除资产点检工单(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EamPointCheckOrderDTO dto) {

        EamPointCheckOrder item = new EamPointCheckOrder();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamPointCheckOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamPointCheckOrder item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());
    }


    /**
     * 根据主键获取资产点检工单信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamPointCheckOrderDTO get(String id) {
        // 查询数据
        return this.baseMapper.queryById(id);
    }

    /**
     * 根据主键获取资产点检工单信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteItem(String id) {
        EamPointCheckOrder item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        this.updateById(item);
    }


    /**
     * 指定模具code查询最后一次点检详情
     *
     * @param assetCode 模具编码
     */
    public List<EamPointCheckDetailDTO> getDetailByAssetCode(String assetCode) {
        return this.baseMapper.getDetailByAssetCode(assetCode);
    }

    /**
     * 获取点检计划最后工单计划时间
     *
     * @param planId
     * @return
     */
    public Date getLastOrderWorkTime(String planId) {
        // 查询条件
        QueryWrapper<EamPointCheckOrder> qw = new QueryWrapper<>();
        qw.lambda().eq(EamPointCheckOrder::getPlanId, planId);
        qw.lambda().eq(EamPointCheckOrder::getDeleted, 0);
        qw.select("max(work_time) as work_time");
        EamPointCheckOrder order = this.baseMapper.selectOne(qw);

        if (order != null) {
            return order.getPlanTime();
        } else {
            return null;
        }

    }

    /**
     * 获取点检计划最后工单计划时间
     *
     * @param planId
     * @return
     */
    public Date getLastOrderPlanTime(String planId) {
        // 查询条件
        QueryWrapper<EamPointCheckOrder> qw = new QueryWrapper<>();
        qw.lambda().eq(EamPointCheckOrder::getPlanId, planId);
        qw.lambda().eq(EamPointCheckOrder::getDeleted, 0);
        qw.select("max(plan_time) as plan_time");
        EamPointCheckOrder order = this.baseMapper.selectOne(qw);

        if (order != null) {
            return order.getPlanTime();
        } else {
            return null;
        }

    }

    public void saveImg(EamPointCheckOrderDTO dto, EamPointCheckOrder item) {
        List<EamPointCheckDetailDTO> listDetails = eamPointCheckDetailService.saveBatchProductRecord(dto.getDetails(), item);

        List<EamPointCheckDetailImgDTO> images = new ArrayList<>();
        List<String> detailIds = new ArrayList<>();
        for (EamPointCheckDetailDTO detail : listDetails) {
            if (detail.getImages() == null) {
                continue;
            }
            for (EamPointCheckDetailImgDTO imageDto : detail.getImages()) {
                imageDto.setPointCheckDetailId(detail.getId());
                images.add(imageDto);
            }
            detailIds.add(detail.getId());
        }

        if (!images.isEmpty()) eamPointCheckDetailImgService.saveBatch(images, detailIds);
    }
}

